import { Button, Form, Input, message, Modal, Select } from 'antd';
import { Space, Table } from 'antd';
import React, { useState, useEffect } from 'react';
// @ts-ignore
import { useModel } from 'umi';
import { Switch } from 'antd';
import { addProject, getLabels, projectList, saveProject } from '@/services/project';
import type { ColumnsType } from 'antd/es/table';
// @ts-ignore
import ProcessSettingList from '@/pages/project/processsettinglist';
const { TextArea } = Input;
import { SettingOutlined } from '@ant-design/icons';
import GridContentLocal from '@/pages/global/gloadding';

const App: React.FC = () => {
  const globalData = useModel('globaldata');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [labelsAndRunners, setLabelAndRunners] = useState<
    {
      label: PRO.Label;
      runners: PRO.Runner[];
    }[]
  >([]);
  const [currentModel, setCurrentModel] = useState<PRO.Project>({
    branch: '',
    create_time: '',
    description: '',
    enable_web_hook: false,
    git_url: '',
    id: 0,
    project_name: '',
    update_time: '',
    webhook_request_key: '',
  });

  const [isShowProcessSettingList, setIsShowProcessSettingList] = useState(false);

  const [dataList, setDataList] = useState<PRO.PageResponse>({
    list: [],
    page: 0,
    page_size: 0,
    total: 0,
  });
  const [projectId, setProjectId] = useState<number>(0);
  const showModal = () => {
    form.resetFields();
    setCurrentModel({
      branch: '',
      create_time: '',
      description: '',
      enable_web_hook: false,
      git_url: '',
      id: 0,
      project_name: '',
      update_time: '',
      webhook_request_key: '',
      labels: '',
    });
    form.setFieldsValue({
      branch: '',
      create_time: '',
      description: '',
      enable_web_hook: false,
      git_url: '',
      id: 0,
      project_name: '',
      update_time: '',
      webhook_request_key: '',
      labels: '',
    });
    setIsModalOpen(true);
  };
  const [form] = Form.useForm();

  const columns: ColumnsType<PRO.Project> = [
    {
      title: '项目名称',
      dataIndex: 'project_name',
      key: 'project_name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: 'GIT地址',
      dataIndex: 'git_url',
      key: 'git_url',
    },
    {
      title: '分支',
      dataIndex: 'branch',
      key: 'branch',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          {/*<a>Invite {record.name}</a>*/}
          {/*<a>Delete</a>*/}
          {record.id}
          <Button
            type="primary"
            icon={<SettingOutlined />}
            onClick={() => {
              // @ts-ignore
              setProjectId(record.id);
              setIsShowProcessSettingList(true);
            }}
          >
            构建配置
          </Button>
          <Button
            type="primary"
            icon={<SettingOutlined />}
            onClick={() => {
              // @ts-ignore
              // if (record.enable_web_hook) {
              //   record.enable_web_hook = 1;
              // } else {
              //   record.enable_web_hook = 0;
              // }
              // @ts-ignore
              setIsModalOpen(true);
              form.resetFields();
              setCurrentModel(record);
              form.setFieldsValue(record);
            }}
          >
            编辑配置
          </Button>
        </Space>
      ),
    },
  ];

  const formValidate = async () => {
    return new Promise((resolve, reject) => {
      form
        .validateFields()
        .then((values) => {
          resolve(values);
        })
        .catch((errorInfo) => {
          reject(errorInfo);
        });
    });
  };
  const loadData = async (page = 1, pageSize = 10) => {
    try {
      globalData.show();
      const res = await projectList({
        page: page,
        page_size: pageSize,
        keyword: '',
      });
      globalData.hidden();
      for (let i in res.list) {
        // @ts-ignore
        if (res.list[i].labels) {
          // @ts-ignore
          res.list[i].labels = JSON.parse(res.list[i].labels);
        } else {
          // @ts-ignore
          res.list[i].labels = [];
        }
      }
      setDataList(res);
      const label = await getLabels();
      setLabelAndRunners(label);
    } catch (e) {
      globalData.hidden();
    }
  };
  useEffect(() => {
    loadData();
  }, []);

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const handleOk = async () => {
    try {
      await formValidate();
      form.submit();
    } catch (error) {}
  };

  // const onFinishFailed = (errorInfo: {}) => {
  //   console.log('Failed:', errorInfo);
  // };

  const handleSubmit = async (values: PRO.Project) => {
    try {
      // @ts-ignore
      values.enable_web_hook = values.enable_web_hook ? 1 : 0;
      values.labels = JSON.stringify(values.labels);
      // 登录
      if (values.id == 0) {
        await addProject(values);
        setIsModalOpen(false);
      } else {
        await saveProject(values);
        setIsModalOpen(false);
      }
      loadData();
    } catch (error) {
      console.log(error);
    }
  };

  const onCopy = (certB64: string) => {
    let oInput = document.createElement('input');
    oInput.value = certB64;
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand('Copy'); // 执行浏览器复制命令
    oInput.remove();
  };

  // @ts-ignore
  // @ts-ignore
  return (
    <GridContentLocal>
      <ProcessSettingList
        projectId={projectId}
        open={isShowProcessSettingList}
        onOk={() => {
          setIsShowProcessSettingList(false);
          loadData();
        }}
        onCancel={() => {
          setIsShowProcessSettingList(false);
        }}
      />
      <Button type="primary" onClick={showModal}>
        新建项目
      </Button>
      <Table
        columns={columns}
        dataSource={dataList.list}
        pagination={{
          showTotal: () => `共 ${dataList?.total} 条`, // 显示总共有多少条
          total: dataList?.total, // 总共有多少条
          onChange: (page, pageSize) => {
            loadData(page, pageSize);
          }, // 页码变化回调函数
          current: dataList.page, // 当前active的页码
          showSizeChanger: true, // 是否显示页面大小变化选择框
        }}
      />
      ;
      <Modal
        forceRender={true}
        title="编辑项目"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={currentModel}
          onFinish={async (values) => {
            await handleSubmit(values as PRO.Project);
          }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="项目名称"
            hidden={true}
            name="id"
            rules={[
              {
                required: true,
                message: '请输入项目名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="项目名称"
            name="project_name"
            rules={[
              {
                required: true,
                message: '请输入项目名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="GIT地址"
            name="git_url"
            rules={[
              {
                required: true,
                message: '请输入GIT地址!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="GIT默认分支"
            name="branch"
            rules={[
              {
                required: true,
                message: '请输入GIT分支!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item label="项目描述" name="description">
            <TextArea rows={4} />
          </Form.Item>
          <Form.Item
            label="启用webhook"
            name="enable_web_hook"
            valuePropName="checked"
            rules={[
              {
                required: true,
                message: '请输入GIT地址!',
              },
            ]}
          >
            <Switch defaultChecked={false} />
          </Form.Item>
          <Form.Item
            label="webhook访问秘钥"
            name="webhook_request_key"
            rules={[
              {
                required: false,
                message: '请输入GIT地址!',
              },
            ]}
          >
            <Input
              onClick={() => {
                if (currentModel.webhook_request_key) {
                  const url =
                    window.location.origin +
                    '/webhook/index?access_token=' +
                    currentModel.webhook_request_key;
                  onCopy(url);
                  message.info(
                    '已自动复制webhook自动构建,将此链接配置到<gitlab或github webhook>可提供自动构建/发布服务',
                  );
                }
              }}
              readOnly={true}
            />
          </Form.Item>

          <Form.Item
            label="标签配置"
            tooltip="设置标签后构建与发布将会带有相同标签的节点运行,此功能用于对集群进行分流"
            name="labels"
            rules={[
              {
                required: false,
                message: '请选择标签!',
              },
            ]}
          >
            <Select
              mode="multiple"
              placeholder="请选择标签"
              defaultValue={[]}
              onChange={() => {}}
              style={{ width: '100%' }}
            >
              {labelsAndRunners.map((item: { label: PRO.Label; runners: PRO.Runner[] }) => {
                // @ts-ignore
                return (
                  // @ts-ignore
                  <Option key={item.label.id} value={item.label.id}>
                    <div title={item.label.description}>标签名:{item.label.label}</div>
                    <div>可用节点数量:{item.runners.length}</div>
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </GridContentLocal>
  );
};

export default App;
